/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2007.
 *
 * Licensed under the Aduna BSD-style license.
 */

package edu.tju.commons.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CollectionUtil {

	/**
	 * Calculates the intersection of two Lists. If either of the Lists contains
	 * duplicate elements, they will be ignored.
	 */
	public static <E> List<E> getIntersection(List<E> firstList,
			List<E> secondList) {
		List<E> result = null;

		if (firstList == secondList) {
			result = firstList;
		} else if (firstList.isEmpty() || secondList.isEmpty()) {
			result = Collections.emptyList();
		} else {
			List<E> largest;
			Set<E> smallest;

			if (firstList.size() > secondList.size()) {
				largest = firstList;
				smallest = new HashSet<E>(secondList);
			} else {
				largest = secondList;
				smallest = new HashSet<E>(firstList);
			}

			result = new ArrayList<E>(smallest.size());
			for (int i = 0; i < largest.size(); i++) {
				E o = largest.get(i);
				if (smallest.contains(o)) {
					result.add(o);
				}
			}
		}

		return result;
	}
}
